import subprocess
from collections import defaultdict

# 定义已知作者列表
known_authors = ["wang-ren-yuan", "dyq", "smiling", "lrq"]

# 执行 Git 命令获取提交的详细信息
result = subprocess.run(
    ["git", "log", "--numstat", "--pretty=format:%H %an"],
    capture_output=True,
    text=True
)

# 分析输出
lines = result.stdout.strip().split('\n')

# 统计数据
code_changes = defaultdict(lambda: {'added': 0, 'deleted': 0, 'commits': 0})

current_commit_hash = ""
current_author_name = ""
for line in lines:
    if line.startswith(' '):  # numstat 信息行以空格开头
        parts = line.split()
        if len(parts) >= 3:  # 确保格式正确
            added_lines = int(parts[0]) if parts[0] != '-' else 0
            deleted_lines = int(parts[1]) if parts[1] != '-' else 0
            filepath = parts[2]

            print(
                f"Commit: {current_commit_hash}, Author: {current_author_name}, File: {filepath}, Added: {added_lines}, Deleted: {deleted_lines}")

            # 更新作者的代码统计
            if current_author_name in known_authors:
                code_changes[current_author_name]['added'] += added_lines
                code_changes[current_author_name]['deleted'] += deleted_lines
                code_changes[current_author_name]['commits'] += 1

    else:  # 是新的提交行
        parts = line.split(maxsplit=1)  # 获取提交哈希和作者
        if len(parts) >= 2:
            current_commit_hash = parts[0]  # 提交哈希
            current_author_name = parts[1].strip()  # 作者名称去掉多余空格
            print(f"New commit detected: {current_commit_hash}, Author: {current_author_name}")

# 输出统计结果
print("Code changes by each author:")
for author in known_authors:
    if author in code_changes:
        stats = code_changes[author]
        total_lines = stats['added'] + stats['deleted']
        print(
            f"{author}: {stats['commits']} commits, {stats['added']} lines added, {stats['deleted']} lines deleted, total {total_lines} lines changed")
    else:
        print(f"{author}: No changes recorded.")